package org.springblade.modules.auth.granter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itextpdf.text.pdf.codec.Base64;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springblade.core.social.props.SocialProperties;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.utils.HttpClientUtils;
import org.springblade.modules.auth.utils.WeChatLoginRequest;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.entity.UserOauth;
import org.springblade.modules.system.service.IUserOauthService;
import org.springblade.modules.system.service.IUserService;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * SocialTokenGranter
 *
 * @author Chill
 */
@Component
@AllArgsConstructor
public class WXAppTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "wx_app";

	private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";
	private static final String GrantType = "authorization_code";
	private static final String AppID = "wx199654f7b439c1b9";
	private static final String AppSecret = "ed92bf62a14e6395ab08fda6ea368d1c";

	private static final Integer AUTH_SUCCESS_CODE = 2000;
	private final IUserOauthService iUserOauthService;
	private final IUserService userService;
	private final SocialProperties socialProperties;

	@SneakyThrows
	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		WeChatLoginRequest loginRequest = (WeChatLoginRequest) tokenParameter.getArgs().getObj("request");
		//		1、用授权码获取微信openId、sessionKey
		JSONObject sessionKeyOpenId = getSessionKeyOrOpenId(loginRequest.getCode());
		// 这里的ErrorCodeEnum是自定义错误字段，可以删除，用自己的方式处理
		//	 	Assert.isTrue(sessionKeyOpenId != null, ErrorCodeEnum.P01.getCode());
		// 获取openId && sessionKey
		String openId = sessionKeyOpenId.getString("openid");
		// 这里的ErrorCodeEnum是自定义错误字段，可以删除，用自己的方式处理
		//		Assert.isTrue(openId != null, ErrorCodeEnum.P01.getCode());
		String sessionKey = sessionKeyOpenId.getString("session_key");

//		2、解密微信用户敏感信息、组装UserOauth



		UserOauth userOauth=new UserOauth();
		QueryWrapper<UserOauth> wxyQueryWrapper = new QueryWrapper<>();
		wxyQueryWrapper.eq("uuid",openId).eq("is_deleted",0);
		List<UserOauth> wxies = iUserOauthService.list(wxyQueryWrapper);
		UserInfo userInfo=new UserInfo();
		userOauth = buildUserOauth(loginRequest, sessionKey, openId);
		if (wxies.size()>0){

			wxies.get(0).setAvatar(userOauth.getAvatar());
			wxies.get(0).setNickname(userOauth.getNickname());
			wxies.get(0).setGender(userOauth.getGender());
			//	wxies.get(0).setUsername(userOauth.getUsername());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			wxies.get(0).setUpdateTime(df.format(new Date()));
			iUserOauthService.updateById(wxies.get(0));
			userInfo.setUserOauth(wxies.get(0));
			return userInfo;
		}else{
			long rangeLong =  RandomUtils.nextLong();
			userOauth.setUserId(rangeLong);
			iUserOauthService.save(userOauth);
			userInfo.setUserOauth(userOauth);
			return userInfo;
		}

//
//		3、查询第三方平台用户信息表（“blade_user_oauth”），不存在则新建，组装UserInfo(包含user表和userOauth表的关联信息)
		//	UserInfo userInfo = userService.userInfo(userOauth);
//		if(Func.isEmpty(userInfo.getUser().getAvatar())){
//			userInfo.getUser().setAvatar(userOauth.getAvatar());
//		}

	}

	// 这里的JSONObject是阿里的fastjson，自行maven导入
	private JSONObject getSessionKeyOrOpenId(String code) throws Exception {
		Map<String, String> requestUrlParam = new HashMap<>();
		// 小程序appId，自己补充
		requestUrlParam.put("appid", AppID);
		// 小程序secret，自己补充
		requestUrlParam.put("secret", AppSecret);
		// 小程序端返回的code
		requestUrlParam.put("js_code", code);
		// 默认参数
		requestUrlParam.put("grant_type", GrantType);

		// 发送post请求读取调用微信接口获取openid用户唯一标识
		String result = HttpClientUtils.doPost(REQUEST_URL, requestUrlParam);
		return JSON.parseObject(result);
	}

	private UserOauth buildUserOauth(WeChatLoginRequest loginRequest, String sessionKey, String openId) {
		UserOauth userOauth = new UserOauth();
		userOauth.setUuid(openId);
		// 组装数据
		if (loginRequest.getRawData() != null) {
			String source = loginRequest.getSource();
			String tenantId = loginRequest.getTenantId();

			RawDataDO rawDataDO = JSON.parseObject(loginRequest.getRawData(), RawDataDO.class);
			userOauth.setSource(source);
			userOauth.setTenantId(tenantId);
			userOauth.setNickname(rawDataDO.getNickName());
			//	userOauth.setUsername(rawDataDO.getNickName());
			userOauth.setAvatar(rawDataDO.getAvatarUrl());
			userOauth.setGender(rawDataDO.getGender());
			userOauth.setLocation(rawDataDO.getProvince() + rawDataDO.getCity() + rawDataDO.getCountry());
		}

		// 解密加密信息，获取unionID
		if (loginRequest.getEncryptedData() != null) {
			JSONObject encryptedData = getEncryptedData(loginRequest.getEncryptedData(), sessionKey, loginRequest.getIv());
			if (encryptedData != null) {
				String unionId = encryptedData.getString("unionId");
//				userOauth.setUnionId(unionId);
			}
		}



		return userOauth;
	}

	private JSONObject getEncryptedData(String encryptedData, String sessionkey, String iv) {
		// 被加密的数据
		byte[] dataByte = Base64.decode(encryptedData);
		// 加密秘钥
		byte[] keyByte = Base64.decode(sessionkey);
		// 偏移量
		byte[] ivByte = Base64.decode(iv);
		try {
			// 如果密钥不足16位，那么就补足.这个if中的内容很重要
			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + 1;
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				return JSONObject.parseObject(result);
			}
		} catch (Exception e) {
//			logger.error("解密加密信息报错", e.getMessage());
		}
		return null;
	}

	@Data
	static public class RawDataDO {
		private String source;
		private String tenantId;
		private String nickName;
		private String avatarUrl;
		private String gender;
		private String city;
		private String country;
		private String province;
	}

}
